<template>
  <div class="monthly-data-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" :inline="true">
        <el-form-item label="采集点">
          <el-select 
            v-model="searchForm.collectionPoint" 
            placeholder="请选择采集点"
            clearable
          >
            <el-option
              v-for="point in collectionPoints"
              :key="point.value"
              :label="point.label"
              :value="point.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="能源类型">
          <el-select 
            v-model="searchForm.energyType" 
            placeholder="请选择能源类型"
            clearable
          >
            <el-option
              v-for="type in energyTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="月份">
          <el-date-picker
            v-model="searchForm.month"
            type="month"
            placeholder="选择月份"
            value-format="YYYY-MM"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
          <el-button type="success" @click="handleExport">
            <el-icon><Download /></el-icon>导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 聚合表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>月度能耗统计</span>
          <span class="month-label">{{ searchForm.month || '当前月份' }}</span>
        </div>
      </template>

      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        :span-method="objectSpanMethod"
        :header-cell-style="{ background: 'rgba(255, 255, 255, 0.05)' }"
        border
      >
        <!-- 采集点 -->
        <el-table-column prop="collectionPoint" label="采集点" width="120" />
        <!-- 能源类型 -->
        <el-table-column prop="energyType" label="能源类型" width="120" />
        <!-- 指标项 -->
        <el-table-column prop="metricName" label="指标项" width="150" />
        <!-- 单位 -->
        <el-table-column prop="unit" label="单位" width="80" />
        <!-- 月度数据 -->
        <el-table-column 
          v-for="day in daysInMonth" 
          :key="day"
          :prop="`day${day}`"
          :label="day"
          width="80"
          align="right"
        >
          <template #default="{ row }">
            {{ formatValue(row[`day${day}`]) }}
          </template>
        </el-table-column>
        <!-- 统计值 -->
        <el-table-column prop="total" label="合计" width="100" align="right">
          <template #default="{ row }">
            <span class="total-value">{{ formatValue(row.total) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="avgValue" label="平均值" width="100" align="right">
          <template #default="{ row }">
            {{ formatValue(row.avgValue) }}
          </template>
        </el-table-column>
        <el-table-column prop="maxValue" label="最大值" width="100" align="right">
          <template #default="{ row }">
            {{ formatValue(row.maxValue) }}
          </template>
        </el-table-column>
        <el-table-column prop="minValue" label="最小值" width="100" align="right">
          <template #default="{ row }">
            {{ formatValue(row.minValue) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'

// 查询表单
const searchForm = reactive({
  collectionPoint: '',
  energyType: '',
  month: ''
})

// 采集点选项
const collectionPoints = [
  { label: 'A采集点', value: 'A' },
  { label: 'B采集点', value: 'B' },
  { label: 'C采集点', value: 'C' }
]

// 能源类型选项
const energyTypes = [
  { label: '原煤', value: 'coal' },
  { label: '电力', value: 'electricity' },
  { label: '天然气', value: 'gas' }
]

// 获取当月天数
const daysInMonth = computed(() => {
  if (!searchForm.month) return []
  const [year, month] = searchForm.month.split('-')
  return new Array(new Date(+year, +month, 0).getDate()).fill(0).map((_, i) => i + 1)
})

// 表格数据
const loading = ref(false)
const tableData = ref([
  {
    collectionPoint: 'A采集点',
    energyType: '原煤',
    metricName: '消耗量',
    unit: 't',
    total: 1234.56,
    avgValue: 41.15,
    maxValue: 50.2,
    minValue: 35.6,
    ...generateDailyData()
  },
  {
    collectionPoint: 'A采集点',
    energyType: '原煤',
    metricName: '库存量',
    unit: 't',
    total: 5678.90,
    avgValue: 189.30,
    maxValue: 200.5,
    minValue: 175.8,
    ...generateDailyData()
  },
  {
    collectionPoint: 'A采集点',
    energyType: '电力',
    metricName: '用电量',
    unit: 'kWh',
    total: 98765.43,
    avgValue: 3292.18,
    maxValue: 3500.6,
    minValue: 3100.2,
    ...generateDailyData()
  },
  // ... 更多数据
])

// 生成每日数据
function generateDailyData() {
  const data: Record<string, number> = {}
  for (let i = 1; i <= 31; i++) {
    data[`day${i}`] = +(Math.random() * 100).toFixed(2)
  }
  return data
}

// 格式化数值
const formatValue = (value: number) => {
  return value?.toFixed(2) || '-'
}

// 合并单元格方法
const objectSpanMethod = ({
  rowIndex,
  columnIndex
}: {
  rowIndex: number
  columnIndex: number
}) => {
  if (columnIndex === 0) {
    // 合并采集点列
    const rowData = tableData.value[rowIndex]
    const prevRow = tableData.value[rowIndex - 1]
    if (prevRow && prevRow.collectionPoint === rowData.collectionPoint) {
      return { rowspan: 0, colspan: 0 }
    }
    const nextRows = tableData.value.slice(rowIndex + 1)
    const rowspan = nextRows.findIndex(r => r.collectionPoint !== rowData.collectionPoint)
    return {
      rowspan: rowspan === -1 ? nextRows.length + 1 : rowspan + 1,
      colspan: 1
    }
  }
  if (columnIndex === 1) {
    // 合并能源类型列
    const rowData = tableData.value[rowIndex]
    const prevRow = tableData.value[rowIndex - 1]
    if (prevRow && prevRow.energyType === rowData.energyType) {
      return { rowspan: 0, colspan: 0 }
    }
    const nextRows = tableData.value.slice(rowIndex + 1)
    const rowspan = nextRows.findIndex(r => r.energyType !== rowData.energyType)
    return {
      rowspan: rowspan === -1 ? nextRows.length + 1 : rowspan + 1,
      colspan: 1
    }
  }
}

// 查询方法
const handleSearch = async () => {
  loading.value = true
  try {
    // 这里添加实际的查询逻辑
    await new Promise(resolve => setTimeout(resolve, 1000))
  } finally {
    loading.value = false
  }
}

// 重置方法
const handleReset = () => {
  searchForm.collectionPoint = ''
  searchForm.energyType = ''
  searchForm.month = ''
  handleSearch()
}

// 导出方法
const handleExport = () => {
  // 这里添加导出逻辑
}
</script>

<style lang="scss" scoped>
.monthly-data-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;

  .search-card,
  .table-card {
    background: rgba(255, 255, 255, 0.05);
    border: none;

    :deep(.el-card__header) {
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      padding: 12px 20px;
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .month-label {
      color: $primary-color;
      font-weight: bold;
    }
  }

  :deep(.el-table) {
    background: transparent;
    
    th.el-table__cell {
      background-color: rgba(255, 255, 255, 0.05);
      border-color: rgba(255, 255, 255, 0.1);
      color: $text-color;
      text-align: center;
    }
    
    td.el-table__cell {
      background-color: transparent;
      border-color: rgba(255, 255, 255, 0.1);
      color: $text-color;
    }

    .total-value {
      color: $primary-color;
      font-weight: bold;
    }
  }
}
</style>
